﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web;
using Icoders.MarketTracker.Core.MasterData;
using Icoders.MarketTracker.Core.Repository.MasterDataRepositories;
using Icoders.MarketTracker.Web.Lib.Util;

namespace Icoders.MarketTracker.Web.Lib.Security.Impl
{
   public class SecurityService : ISecurityService
   {
       private IUserRepository _userRepository;
       private IFrsAssignRepository _fsrAssignRepository;

       public SecurityService(IUserRepository userRepository, IFrsAssignRepository fsrAssignRepository)
       {
           _userRepository = userRepository;
           _fsrAssignRepository = fsrAssignRepository;
       }

       public bool Authenticate(string username, string password)
       {
           return _userRepository.IsLogin(username, password);
       }
       
       public CustomPrincipal ConstructCustomPrincipal(IIdentity identity)
       {
           User user = _userRepository.GetByUsername(identity.Name);
           if (user == null){
               
               return null;
           }
           CustomIdentity customIdentity = null;
           if(user.UserTypeId==(int)UserType.MobileAppUser)
           {
               var fsrassign = _fsrAssignRepository.GetByUser(user.Id);
               int clentId = fsrassign != null ? fsrassign.ClientId : 0;
               int userid = user != null ? user.Id : 0;
               int areaId=fsrassign != null ? fsrassign.AreaId : 0;
               customIdentity = new FsrCustomIdentity(identity.IsAuthenticated, identity.AuthenticationType, identity.Name,
                                                 user.ChangePass, areaId, clentId, userid);

           }
           else if (user.UserTypeId == (int)UserType.WebAppUser)
           {
               customIdentity = new CustomIdentity(identity.IsAuthenticated, identity.AuthenticationType, identity.Name, user.ChangePass);
           }
           //var customIdentity = new CustomIdentity(identity.IsAuthenticated, identity.AuthenticationType, identity.Name,user.ChangePass);
           foreach (string role in user.Roles)
               customIdentity.Roles.Add(role);
           return new CustomPrincipal(customIdentity);

       }
    }
}
